package com.jsoft.jsofted.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsoft.jsofted.framework.annotation.JwtToken;
import com.jsoft.jsofted.framework.controller.DataController;
import com.jsoft.jsofted.framework.service.CocService;
import com.jsoft.jsofted.framework.utils.PageResult;
import com.jsoft.jsofted.framework.utils.ResponseModel;
import com.jsoft.jsofted.platform.entity.ProjectInfoEntity;
import com.jsoft.jsofted.platform.service.ProjectInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 全部的增删改查基础代码框架已经写好
 * 见：DataController
 *
 * 需要特殊处理的覆盖sevice层
 */
@RestController
@RequestMapping("/jsofted/project")
public class ProjectInfoController extends DataController<ProjectInfoEntity> {

    @Autowired
    private ProjectInfoService projectInfoService;

    @Override
    public CocService<ProjectInfoEntity> cocService() {
        return projectInfoService;
    }
    /////////////////////////////////////////////diboot方式///////////////////////////////////////////////////////////
    /**
     * 使用diboot的保存
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/saveByEntityByDiboot")
    public ResponseModel saveByEntityByDiboot(@RequestBody(required = false) ProjectInfoEntity projectInfoEntity) {
        //super._add返回ResponseModel
        return super._add(projectInfoEntity);
    }
    /**
     * 自定义query增强版
     * @param queryParams
     * @return
     */
    @JwtToken
    @RequestMapping("/queryEnhance")
    public ResponseModel query(@RequestBody(required = false) LinkedHashMap queryParams) {
        return this._query(queryParams);
    }

    protected ResponseModel _query(LinkedHashMap queryParams) {
        /**
         *  CocServiceImpl里面queryPageResult的parseQueryWrapper,如：
         *        CocQueryWrapper queryWrapper = parseQueryWrapper(queryParams); //CocServiceImpl类280行
         *
         *  parseQueryWrapper实际真正调用ProjectInfoServiceImpl重写的parseQueryWrapper
         *
         */
        PageResult pageResult = cocService().queryPageResult(queryParams);

        /**
         * 不存在数据库的字段，标注：@TableField(exist = false)
         * 如：securityCategory1Name、securityCategory2Name、deptName
         * 设置数据库securityCategory1、securityCategory2、dept对应的名字，因为表里面只保存了这几个的ID，具体的名字在别的表里面
         * 这里模拟查询他们的真正的表的对应的名字
         */
        List<ProjectInfoEntity> list = (List<ProjectInfoEntity>) pageResult.getResult();
        if(!ObjectUtils.isEmpty(list)){
            list.parallelStream().forEach(aProjectInfoEntity ->{
                //实际这里查询他们id对应的具体表的名字
                //实际查询DB，这里模拟....
                aProjectInfoEntity.setDeptIdName("deptId对应的部门名字");
                aProjectInfoEntity.setSecurityCategory1Name("securityCategory1 ID值对应的名字");
                aProjectInfoEntity.setSecurityCategory2Name("securityCategory2 ID值对应的名字");
            });
        }
        return ResponseModel.makeSuccess(null, pageResult);
    }

    /////////////////////////////////////////////mybatis方式///////////////////////////////////////////////////////////
    /**
     * 比如（查询第1页7条数据，条件是projName == "项目名称1234"）：
     * http://localhost:8080/jsofted/project/selectProjectInfoEntityList/1/7
     * projectInfoEntity = {
     *       "projName": "项目名称1234"
     *  }
     *       又比如（查询第1页7条数据，没有条件，全查：
     *       http://localhost:8080/jsofted/project/selectProjectInfoEntityList/1/7
     *       projectInfoEntity = {
     *       }
     * mybatis查询-分页
     * @param projectInfoEntity
     * @return 查询结果
     */
    @JwtToken
    @PostMapping("/selectProjectInfoEntityList/{currentPage}/{pageSize}")
    public ResponseModel selectProjectInfoEntityList(
            @PathVariable("currentPage") int currentPage,
            @PathVariable("pageSize") int pageSize,
            @RequestBody ProjectInfoEntity projectInfoEntity//查询条件项
    )
    {
        Page<ProjectInfoEntity> page = projectInfoService.selectProjectInfoEntityList(
                new Page<ProjectInfoEntity>(currentPage,pageSize),
                projectInfoEntity);
        return ResponseModel.makeSuccess(page);
    }
    /**
     * 比如：
     * http://localhost:8080/jsofted/project/insertProjectInfoEntity
     * projectInfoEntity = {
     * 	"id":0,//ID为0，表示MySQL不存在
     * 	"coopTimes": "0",
     * 	"creditStatus": "1",
     * 	"customerName": "企业名称1234",
     * 	"customerRegAddress": "企业住所1234",
     * 	"deptId": "0",
     * 	"enterTime": "2021-07-24T15:23:23.942Z",
     * 	"finishTime": "2021-07-24T15:23:26.356Z",
     * 	"firstPayAmount": 3,
     * 	"gainStatus": "1",
     * 	"intendAmount": 2,
     * 	"investAmount": 2,
     * 	"loanAmount": 3,
     * 	"needAudit": "1",
     * 	"otherRequire": "合同要附加的企业其他 要求",
     * 	"projAddressName": "项目所在地1234",
     * 	"projName": "项目名称1234",
     * 	"prospect": "项目发展前景1234",
     * 	"psAmount": 3,
     * 	"reportMngUnit": "1",
     * 	"reportReview": "1",
     * 	"sdTime": "2021-07-24T15:23:29.639Z",
     * 	"securityAwareStatus": "1",
     * 	"securityCategory1": "0",
     * 	"securityCategory2": "0",
     * 	"securityMngStatus": "1",
     * 	"serviceRange": "项目技术服务范围",
     * 	"setupTime": "2021-07-24T15:22:04.415Z",
     * 	"createTime":"2021-07-24T15:22:04.415Z",
     * 	"updateTime":"2021-07-24T15:22:04.415Z",
     * 	"sortValue":"0"
     * }
     * mybatis插入
     * @param projectInfoEntity
     * @return 插入数量
     */
    @JwtToken
    @PostMapping("/insertProjectInfoEntity")
    public ResponseModel insertProjectInfoEntity(@RequestBody ProjectInfoEntity projectInfoEntity) {
        //主键id，雪花算法（废弃MySQL自增主键）
        projectInfoEntity.setId(IdWorker.getId());
        int row = projectInfoService.insertProjectInfoEntity(projectInfoEntity);
        return ResponseModel.makeSuccess(row);
    }
    /**
     * 比如：
     * http://localhost:8080/jsofted/project/updateProjectInfoEntity
     * projectInfoEntity = {
     * 	"id":1418960815839113217,//ID有值，大于0，表示存在
     * 	"coopTimes": "0",
     * 	"creditStatus": "1",
     * 	"customerName": "企业名称1234(更新企业名称)",
     * 	"customerRegAddress": "企业住所1234",
     * 	"deptId": "0",
     * 	"enterTime": "2021-07-24T15:23:23.942Z",
     * 	"finishTime": "2021-07-24T15:23:26.356Z",
     * 	"firstPayAmount": 3,
     * 	"gainStatus": "1",
     * 	"intendAmount": 2,
     * 	"investAmount": 2,
     * 	"loanAmount": 3,
     * 	"needAudit": "1",
     * 	"otherRequire": "合同要附加的企业其他 要求",
     * 	"projAddressName": "项目所在地1234",
     * 	"projName": "项目名称1234",
     * 	"prospect": "项目发展前景1234",
     * 	"psAmount": 3,
     * 	"reportMngUnit": "1",
     * 	"reportReview": "1",
     * 	"sdTime": "2021-07-24T15:23:29.639Z",
     * 	"securityAwareStatus": "1",
     * 	"securityCategory1": "0",
     * 	"securityCategory2": "0",
     * 	"securityMngStatus": "1",
     * 	"serviceRange": "项目技术服务范围",
     * 	"setupTime": "2021-07-24T15:22:04.415Z",
     * 	"createTime":"2021-07-24T15:22:04.415Z",
     * 	"updateTime":"2021-07-24T15:22:04.415Z",
     * 	"sortValue":"0"
     * }
     * mybatis更新(依据id)
     * @param projectInfoEntity
     * @return 更新数量
     */
    @JwtToken
    @PostMapping("/updateProjectInfoEntity")
    public ResponseModel updateProjectInfoEntity(@RequestBody ProjectInfoEntity projectInfoEntity) {
        int row = projectInfoService.updateProjectInfoEntity(projectInfoEntity);
        return ResponseModel.makeSuccess(row);
    }
    /**
     * 比如：
     * http://localhost:8080/jsofted/project/deleteProjectInfoEntityById?id=1419114596799135746
     * 删除
     * @param id
     * @return 删除数量
     */
    @JwtToken
    @PostMapping("/deleteProjectInfoEntityById")
    public ResponseModel deleteProjectInfoEntityById(@RequestParam Long id) {
        int row = projectInfoService.deleteProjectInfoEntityById(id);
        return ResponseModel.makeSuccess(row);
    }
    /**
     * 比如：
     * http://localhost:8080/jsofted/project/deleteProjectInfoEntityByIds
     * [1416702131817684993,1418955087661281282]
     * 删除-批量
     * @param ids
     * @return 删除数量
     */
    @JwtToken
    @PostMapping("/deleteProjectInfoEntityByIds")
    public ResponseModel deleteProjectInfoEntityByIds(@RequestBody List<Long> ids) {
        int row = projectInfoService.deleteProjectInfoEntityByIds(ids);
        return ResponseModel.makeSuccess(row);
    }

    /**
     * 更新或者保存
     * id为准,id不为null而且大于0就是更新，否则保存
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/insertOrUpdateProjectInfoEntity")
    public ResponseModel insertOrUpdateProjectInfoEntity(@RequestBody ProjectInfoEntity projectInfoEntity) {
        if(ObjectUtils.isEmpty(projectInfoEntity)){
            return ResponseModel.makeError("参数不可以为空！");
        }
        //存在ID，更新
        int row = 0;//成功的行数
        if( null != projectInfoEntity.getId() && projectInfoEntity.getId() > 0){
            row = projectInfoService.updateProjectInfoEntity(projectInfoEntity);
        }
        else{
            //主键id，雪花算法（废弃MySQL自增主键）
            //MySQL不存在数据，设置id，mybatis-plus会去保存
            projectInfoEntity.setId(IdWorker.getId());
            row = projectInfoService.insertProjectInfoEntity(projectInfoEntity);
        }
        return ResponseModel.makeSuccess(row);
    }
    /////////////////////////////////////////////mybatis-plus方式///////////////////////////////////////////////////////////
    //代码->com.baomidou.mybatisplus.extension.service.IService

    /**
     * 参数同上面的mybatis方式
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/selectProjectInfoListByEntityByPlus/{currentPage}/{pageSize}")
    public ResponseModel selectProjectInfoListByEntityByPlus(
            @PathVariable("currentPage") int currentPage,
            @PathVariable("pageSize") int pageSize,
            @RequestBody ProjectInfoEntity projectInfoEntity//查询条件项
    ) {
        Page<ProjectInfoEntity> page = projectInfoService.page(
                new Page<ProjectInfoEntity>(currentPage,pageSize),
                new QueryWrapper<ProjectInfoEntity>(projectInfoEntity)//projectInfoEntity不为null的就是条件项
        );
        return ResponseModel.makeSuccess(page);
    }
    /**
     * 参数同上面的mybatis方式
     * 使用mybatis-plus的保存
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/saveByEntityByPlus")
    public ResponseModel saveByEntityByPlus(@RequestBody ProjectInfoEntity projectInfoEntity) {
        //主键id，雪花算法（废弃MySQL自增主键）
        projectInfoEntity.setId(IdWorker.getId());
        boolean flag = projectInfoService.save(projectInfoEntity);
        return ResponseModel.makeSuccess(flag);
    }
    /**
     * 参数同上面的mybatis方式
     * 使用mybatis-plus的保存
     * 根据id
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/updateByEntityByPlus")
    public ResponseModel updateByEntityByPlus(@RequestBody ProjectInfoEntity projectInfoEntity) {
        boolean flag = projectInfoService.updateById(projectInfoEntity);
        return ResponseModel.makeSuccess(flag);
    }

    /**
     * 参数同上面的mybatis方式
     * 删除根据id
     * @param id
     * @return
     */
    @JwtToken
    @PostMapping("/deleteIdByEntityByPlus")
    public ResponseModel deleteIdByEntityByPlus(@RequestParam Long id) {
        boolean flag = projectInfoService.removeById(id);
        return ResponseModel.makeSuccess(flag);
    }

    /**
     * 参数同上面的mybatis方式
     * 删除根据ids
     * @param ids
     * @return
     */
    @JwtToken
    @PostMapping("/deleteIdsByEntityByPlus")
    public ResponseModel deleteIdsByEntityByPlus(@RequestBody List<Long> ids) {
        boolean flag = projectInfoService.removeByIds(ids);
        return ResponseModel.makeSuccess(flag);
    }

    /**
     * 更新或者保存
     * id为准,id不为null而且大于0就是更新，否则保存
     * @param projectInfoEntity
     * @return
     */
    @JwtToken
    @PostMapping("/insertOrUpdateProjectInfoEntityByEntityByPlus")
    public ResponseModel insertOrUpdateProjectInfoEntityByEntityByPlus(@RequestBody ProjectInfoEntity projectInfoEntity) {
        if(ObjectUtils.isEmpty(projectInfoEntity)){
            return ResponseModel.makeError("参数不可以为空！");
        }
        //存在ID，更新
        if( null != projectInfoEntity.getId() && projectInfoEntity.getId() > 0){
            //更新，id>0,已经存在MySQL，mybatis-plus根据id更新
        }
        else{
            //主键id，雪花算法（废弃MySQL自增主键）
            //MySQL不存在数据，设置id，mybatis-plus会去保存
            projectInfoEntity.setId(IdWorker.getId());
        }
        //mybatis-plus方式更保守一点，会根据id校验数据库
        boolean flag = projectInfoService.saveOrUpdate(projectInfoEntity);
        return ResponseModel.makeSuccess(flag);
    }
}
